package com.content.scaffold.common.mybatis;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaojl
 *  与supperQuery类似
 *  todo 后面再实现
 */
@Data
@Slf4j
public class CommonQuery {
    public static final String ASC = "asc";
    public static final String DESC = "desc";

    /**
     * 页数，默认为1
     */
    protected Integer page = 1;

    /**
     * 每页大小，默认为10
     */
    protected Integer size = 10;

    /**
     * 排序方式，可选择：desc asc，默认asc
     */
    protected String order = ASC;

    /**
     * 排序字段
     */
    protected String sort;

    /**
     * 多种排序条件，如果order和sort中已经传入参数，则此参数无效
     */
    protected List<OrderItem> orderItems;

    /**
     * 查询参数列表
     */
    @Getter
    protected List<QueryParam> queryParams = new ArrayList<>();

    public CommonQuery addParam(String key, Object value) {
        queryParams.add(new QueryParam(key, value));
        return this;
    }

    public Page getPageEntity() {
        Page<?> page = new Page<>(this.getPage(), this.getSize());
        if (StringUtils.isNotBlank(this.getSort())) {
            OrderItem orderItem = SuperQuery.ASC.equalsIgnoreCase(this.getSort())
                    ? OrderItem.asc(this.getSort())
                    : OrderItem.desc(this.getSort());
            page.addOrder(orderItem);
        } else if (this.getOrderItems() != null && !this.getOrderItems().isEmpty()) {
            page.setOrders(this.getOrderItems());
        }
        return page;
    }

    public void setParams() {
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            // 设置为可访问
            field.setAccessible(true);
            try {
                Object value = field.get(this);
                // 避免添加空值
                if (value != null) {
                    addParam(field.getName(), value);
                }
            } catch (IllegalAccessException e) {
                log.error("设置参数出错", e);
            }
        }
    }

}
